package com.linkage.jz.bankruptcy.activity.Project;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FileAdapter;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProTaskDetail;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPopupMenu;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;


/**
 * @author AFAP
 * 任务详情
 */
public class ProTaskDetailActivity extends BaseActivity implements OnClickListener {
    public static final String KEY_ID = "key_id";
    private String mID;
    private ProTaskDetail mTaskDetail;
    private RecyclerView mFileRecyclerView;
    private List<TaskAtta> mFileList = new ArrayList<>();
    private FileAdapter mFileAdapter;

    private TextView tv_task_title, tv_creator_name, tv_create_time, tv_task_status, tv_task_content,
            tv_task_executor, tv_task_deadline, tv_task_finish_time, tv_task_feedback;
    private ImageView img_task_executor;
    private View area_compete,recycler_files_title,recycler_files_view;

    private CommonPopupMenu popupMenu;
    private boolean editTask = false;
    private boolean deleteTask = false;
    private boolean execute = false;


    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_task_detail);
        super.onCreate(savedInstanceState);
        titlebar_title.setText("任务详情");

        EventBus.getDefault().register(this);
        mID = getIntent().getStringExtra(KEY_ID);

        getDetail();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_TASK)) {
            finish();
        }
    }

    @Override
    public void initView() {
        tv_task_title = findViewById(R.id.tv_task_title);
        tv_creator_name = findViewById(R.id.tv_creator_name);
        tv_create_time = findViewById(R.id.tv_create_time);
        tv_task_status = findViewById(R.id.tv_task_status);
        tv_task_content = findViewById(R.id.tv_task_content);
        tv_task_executor = findViewById(R.id.tv_task_executor);
        tv_task_deadline = findViewById(R.id.tv_task_deadline);
        tv_task_finish_time = findViewById(R.id.tv_task_finish_time);
        tv_task_feedback = findViewById(R.id.tv_task_feedback);
        img_task_executor = findViewById(R.id.img_task_executor);
        recycler_files_title = findViewById(R.id.recycler_files_title);
        area_compete = findViewById(R.id.area_compete);

        recycler_files_view = findViewById(R.id.recycler_files_view);
        mFileRecyclerView = findViewById(R.id.recycler_files);
        mFileRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mFileAdapter = new FileAdapter(this, mFileList);
//        mFileAdapter.openLoadAnimation();
        mFileRecyclerView.setAdapter(mFileAdapter);
//        mFileAdapter.setOnItemChildClickListener((adapter, view, position) -> {
//            switch (view.getId()) {
//                case R.id.tv_file_name:
//                    openOrDownloadFile(mFileList.get(position), ProTaskDetailActivity.this);
//                    break;
//            }
//        });
    }


    private CommonPromptDialog replyDialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_task_finish:
                replyDialog = new CommonPromptDialog(this, CommonPromptDialog.TYPE_EDIT_MULT);
                replyDialog.setTitle("确定是否任务完成？");
                replyDialog.setEditHint("请输入任务回馈信息（可不填）");
                replyDialog.setPositiveClickListener("确定", view1 -> {
                    replyDialog.dismiss();
                    String feedback = replyDialog.dialog_prompt_edit.getText().toString().trim();
                    completeTask(feedback);
                });
                replyDialog.setNegativeClickListener("取消", view12 -> replyDialog.dismiss());
                replyDialog.show();
                break;
            default:
                break;
        }
    }

    private void refreshDetail() {
        tv_task_title.setText(mTaskDetail.getTaskName());
        tv_creator_name.setText("创建人：" + mTaskDetail.getCreator().getUsername());
        tv_create_time.setText(DateFormatUtils.long2Str(mTaskDetail.getOpAt() * 1000, true));
        tv_task_status.setText(mTaskDetail.getStatus().getText());
        if ("2".equalsIgnoreCase(mTaskDetail.getStatus().getValue())) {
            tv_task_status.setTextColor(getResources().getColor(R.color.pro_task_status_ywc));
        } else {
            tv_task_status.setTextColor(getResources().getColor(R.color.pro_task_status_wcl));
        }
        tv_task_content.setText(mTaskDetail.getTaskContent());
        tv_task_executor.setText(mTaskDetail.getExecutor().getUsername());
        tv_task_deadline.setText(DateFormatUtils.long2Str(mTaskDetail.getDeadlineTime(), true));


        Glide.with(this).load(mTaskDetail.getExecutor().getAvatar())
                .bitmapTransform(new CropCircleTransformation(this))
                .placeholder(R.drawable.logo)
                .into(img_task_executor);

        // 非完成状态
        if (!TextUtils.equals(mTaskDetail.getStatus().getValue(), "2")) {
            if (mTaskDetail.isExecutor()) {
                findViewById(R.id.btn_task_finish).setVisibility(View.VISIBLE);
            }
        } else {
            tv_task_finish_time.setText(DateFormatUtils.long2Str(mTaskDetail.getFinishTime() * 1000, true));
            tv_task_feedback.setText(mTaskDetail.getFeedbackMessage());
//            findViewById(R.id.area_task_feedback).setVisibility(View.VISIBLE);
        }
        if (mTaskDetail.getTaskAtta() != null && mTaskDetail.getTaskAtta().size()>0) {
            mFileList.addAll(mTaskDetail.getTaskAtta());
            FileAdapter.sorFiles(mFileList, true);
            mFileAdapter.notifyDataSetChanged();
        }else{
            recycler_files_title.setVisibility(View.GONE);
            recycler_files_view.setVisibility(View.GONE);
        }


        if ("2".equalsIgnoreCase(mTaskDetail.getStatus().getValue())) {
            area_compete.setVisibility(View.VISIBLE);
        } else {
            area_compete.setVisibility(View.GONE);
        }


        List<String> menus = new ArrayList<>();
        if (editTask) {
            menus.add("编辑");
        }
        if (deleteTask) {
            menus.add("删除");
        }
        if (menus.size() == 0) {
            titlebar_menu.setVisibility(View.GONE);
            return;
        }

        popupMenu = new CommonPopupMenu(this, menus);
        titlebar_menu.setVisibility(View.VISIBLE);
        titlebar_menu.setOnClickListener(v -> {
            popupMenu.showLocation(R.id.titlebar_menu);
            popupMenu.setOnItemClickListener((index, str) -> {
                if (TextUtils.equals(str, "编辑")) {
                    Intent intent = new Intent(ProTaskDetailActivity.this, CreateProTaskActivity.class);
                    intent.putExtra(CreateProTaskActivity.KEY_ACTION, "edit");
                    intent.putExtra(CreateProTaskActivity.KEY_TASK, mTaskDetail);
                    startActivity(intent);
                } else if (TextUtils.equals(str, "删除")) {
                    //删除
                    Dialog tipDialog = new AlertDialog
                            .Builder(ProTaskDetailActivity.this)
                            .setTitle("提示")
                            .setMessage("确认删除当前任务吗？")
                            .setPositiveButton(R.string.confirm, (dialog, which) -> deleteTask()).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).create();

                    tipDialog.setCancelable(false);
                    tipDialog.show();
                }
            });
        });
    }

    private void getDetail() {
        Network
                .getAPIService()
                .getTaskDetail(getUserToken(), mID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");

                        editTask = data.getAsJsonObject("auth").get("editTask").getAsBoolean();
                        deleteTask = data.getAsJsonObject("auth").get("deleteTask").getAsBoolean();
                        execute = data.getAsJsonObject("auth").get("executeTask").getAsBoolean();


//                        editTask = false;
//                        deleteTask = false;
//                        execute = true;

                        mTaskDetail = ProTaskDetail.parse(data.getAsJsonObject("taskDetail"));
                        JsonObject auth = data.getAsJsonObject("auth");
                        mTaskDetail.setExecutor(auth.get("executeTask").getAsBoolean());
                        mTaskDetail.setCreator(auth.get("editTask").getAsBoolean());
                        refreshDetail();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }

    private void completeTask(String feedback) {
        if (!execute) {
            ToastUtil.showShort("您没有完成任务权限");
            return;
        }

        Network
                .getAPIService()
                .completeTask(getUserToken(), mID, feedback)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(() -> mShapeLoadingDialog.show())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TASK);
                        EventBus.getDefault().post(event);
                        ToastUtil.showShort("任务已完成");
                        finish();
                    }


                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });

    }

    private void deleteTask() {
        Network
                .getAPIService()
                .deleteTask(getUserToken(), mID)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mShapeLoadingDialog.show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TASK);
                        EventBus.getDefault().post(event);
                        ToastUtil.showShort("公示已删除");
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }

}
